package com.woniu.woniuk16.service.impl;

import com.woniu.woniuk16.commens.ComUtil;
import com.woniu.woniuk16.dto.UserDto;
import com.woniu.woniuk16.dto.WoniuUserDetails;
import com.woniu.woniuk16.entity.WoniuAccount;
import com.woniu.woniuk16.entity.WoniuUser;
import com.woniu.woniuk16.mapper.WoniuUserMapper;
import com.woniu.woniuk16.param.SaveUserParam;
import com.woniu.woniuk16.service.WoniuAccountService;
import com.woniu.woniuk16.service.WoniuUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tiangle
 * @since 2021-12-16
 */
@Service
public class WoniuUserServiceImpl extends ServiceImpl<WoniuUserMapper, WoniuUser> implements WoniuUserService {
    @Autowired
    private WoniuAccountService woniuAccountService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDto getOneUser() {
        WoniuUserDetails woniuUserDetails = (WoniuUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        WoniuUser byId = getById(woniuUserDetails.getUserId());
        UserDto userDto = ComUtil.copyProperties(byId, UserDto.class);
        return userDto;
    }

    @Override
    public boolean savaUser(SaveUserParam saveUserParam) {
        String userName = saveUserParam.getUserName();
        WoniuUser build = WoniuUser.builder().userName(userName).userTime(ComUtil.nowDate()).build();
        save(build);
        build.setUserNum("WNXY"+ComUtil.getNumById(build.getUserId()));
        saveOrUpdate(build);

        WoniuAccount wa = new WoniuAccount();
        wa.setUserId(build.getUserId());
        wa.setAccountName(build.getUserNum());
        String encode = passwordEncoder.encode("123");
        wa.setAccountPass(encode);
        woniuAccountService.save(wa);

        return true;
    }
}
